<template>
  <div class="user">
    <basic-container>
      <avue-crud
        :option="option"
        ref="crud"
        v-model="form"
        :page.sync="page"
        @on-load="getList"
        @size-change="sizeChange"
        @current-change="currentChange"
        :table-loading="listLoading"
        @search-change="handleFilter"
        @search-reset="handleReset"
        @refresh-change="handleRefreshChange"
        @row-update="update"
        @row-save="create"
        :before-open="handleOpenBefore"
        :data="list"
      >
        <template slot="pic" slot-scope="scope">
          <el-avatar shape="square" :size="60" :src="scope.row.avatar" />
        </template>
        <template slot-scope="scope" slot="avatarsForm">
          <div class="upload-box">
            <el-upload action="/admin/sys-file/upLodeFileAdd" :show-file-list="false" :on-success="handleAvatarSuccess">
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </template>
        <template slot="menuLeft">
          <el-button v-if="sys_user_add" class="filter-item" @click="handleCreate" size="small" type="primary" icon="el-icon-edit">添加</el-button>
        </template>
        <template slot="username" slot-scope="scope">
          <span>{{scope.row.username}}</span>
        </template>
        <template slot="role" slot-scope="scope">
          <span v-for="(role,index) in scope.row.roleList" :key="index">
            <el-tag>{{role.roleName}}</el-tag>&nbsp;&nbsp;
          </span>
        </template>
        <template slot="deptId" slot-scope="scope">{{scope.row.deptName}}</template>
        <template slot="lockFlag" slot-scope="scope">
          <el-tag>{{scope.label}}</el-tag>
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button v-if="sys_user_edit" size="small" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row,scope.index)">编辑</el-button>
          <el-button v-if="sys_user_del" size="small" type="text" icon="el-icon-delete" @click="deletes(scope.row,scope.index)">删除</el-button>
          <el-button v-if="sys_user_edit_password" size="small" type="text" icon="el-icon-refresh-right" @click="resetPassword(scope.row)">密码重置</el-button>
          <el-button v-if="sys_user_unLock" size="small" type="text" icon="el-icon-unlock" @click="unLock(scope.row,scope.index)">解除锁定</el-button>
        </template>
        <template slot="deptIdForm" slot-scope="scope">
          <avue-input-tree v-model="form.deptId" placeholder="请选择所属部门" :node-click="getNodeData" :dic="treeDeptData" :props="defaultProps"></avue-input-tree>
        </template>
        <template slot="roleForm" slot-scope="scope">
          <avue-select v-model="role" multiple placeholder="请选择角色" :dic="rolesOptions" :props="roleProps"></avue-select>
        </template>
        <template slot="search" slot-scope="scope">
          <el-col :span="12">
            <el-row>
              <el-col :span="12" align="right" valign="bottom">
                <el-form-item label="部门">
                  <avue-input-tree v-model="searchDeptId" placeholder="请选择所属部门" :node-click="getNodeData" :dic="treeDeptData" :props="defaultProps"></avue-input-tree>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态">
                  <avue-radio v-model="searchLockFlag" :dic="lockFlagDicData"></avue-radio>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </template>
      </avue-crud>
    </basic-container>
    <reset-password ref="resetPassword"></reset-password>
  </div>
</template>

<script>
import { addObj, delObj, fetchList, putObj, putUser } from "~/admin/api/user"
import { UnLock } from "~/api/login"
import { tableOption } from '~/admin/const/user'
import { deptRoleList } from "~/admin/api/role"
import resetPassword from './reset-password'
import { fetchTree } from "~/admin/api/dept"
import { mapGetters } from "vuex"

export default {
  name: "table_user",
  components: { resetPassword },
  data () {
    return {
      //自定义搜索
      searchDeptId: "",
      searchLockFlag: "",

      lockFlagDicData: [{
        label: '有效',
        value: '0'
      }, {
        label: '无效',
        value: '2'
      }, {
        label: '锁定',
        value: '9'
      }],

      imageUrl: '',
      option: tableOption,
      treeDeptData: [],
      checkedKeys: [],
      roleProps: {
        label: "roleName",
        value: 'roleId'
      },
      defaultProps: {
        label: "name",
        value: 'id',
      },
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条,
        isAsc: false//是否倒序
      },
      list: [],
      listLoading: true,
      role: [],
      form: {},
      searchFrom: {},
      rolesOptions: [],
      editUrl: '',  //编辑用户时，用户头像的原始url
    }
  },
  computed: {
    ...mapGetters(["permissions"])
  },
  mounted: function () {
    this.handleDept()
  },
  watch: {
    role () {
      this.form.role = this.role
    }
  },
  created () {
    this.sys_user_add = this.permissions["sys_user_add"]
    this.sys_user_edit = this.permissions["sys_user_edit"]
    this.sys_user_del = this.permissions["sys_user_del"]
    this.sys_user_edit_password = this.permissions["sys_user_edit_password"]

    this.sys_user_unLock = this.permissions["sys_user_unLock"]
  },
  methods: {
    handleAvatarSuccess (res, file) {
      this.editUrl = res.data.url
      console.log("文件上传")
      console.log(res)
      this.imageUrl = URL.createObjectURL(file.raw)
      console.log(this.imageUrl)
    },
    resetPassword (row) {
      this.$refs.resetPassword.show(row)
    },

    getList (page, params) {
      this.listLoading = true
      fetchList(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchFrom)).then(response => {
        this.list = response.data.data.records

        //alert(JSON.stringify(this.list));

        this.page.total = response.data.data.total
        this.listLoading = false
      })
    },
    getNodeData (data) {
      deptRoleList().then(response => {
        this.rolesOptions = response.data.data
      })
    },
    handleDept () {
      fetchTree().then(response => {
        this.treeDeptData = response.data.data
      })
    },
    sizeChange (pageSize) {
      this.page.pageSize = pageSize
    },
    currentChange (current) {
      this.page.currentPage = current
    },
    handleFilter (param, done) {
      this.searchFrom = param;
      //自定义条件
      this.searchFrom.deptId = this.searchDeptId;
      this.searchFrom.lockFlag = this.searchLockFlag;
      this.getList(this.page, param)
      done()
    },
    handleReset () {
      this.searchFrom = {};
      this.searchDeptId = "";
      this.searchLockFlag = "";
    },
    handleRefreshChange () {
      console.log(111)
      this.getList(this.page)
    },
    handleCreate () {
      this.$refs.crud.rowAdd()
      this.editUrl = ''
      this.imageUrl = ''
      Object.keys(this.form).forEach(key => {
        if (this.form[key]) {
          if (this.form[key] instanceof Array) {
            this.form[key] = []
          } else if (typeof this.form[key] === 'string' || typeof this.form[key] === 'number') {
            this.form[key] = ''
          }
        }
      })
      console.log(this.form)
    },
    handleOpenBefore (show, type) {
      window.boxType = type
      this.handleDept()
      if (['edit', 'views'].includes(type)) {
        this.role = []
        for (var i = 0; i < this.form.roleList.length; i++) {
          this.role[i] = this.form.roleList[i].roleId
        }
        deptRoleList().then(response => {
          this.rolesOptions = response.data.data
        })
      } else if (type === 'add') {
        this.role = []
      }
      show()
    },
    async handleUpdate (row, index) {
      this.$refs.crud.rowEdit(row, index)
      this.editUrl = this.form.avatar
      this.imageUrl = this.form.avatar
      //this.form.password = undefined
    },
    create (row, done, loading) {
      this.form.avatar = this.editUrl
      this.form.avatars = ''
      addObj(this.form).then(() => {
        this.getList(this.page)
        done()
        this.$notify.success('创建成功')
      }).catch(() => {
        loading()
      })
    },
    update (row, index, done, loading) {
      let params = Object.assign({}, this.form)
      params.avatar = this.editUrl
      putUser(params).then(() => {
        this.getList(this.page)
        done()
        this.editUrl = ''
        this.imageUrl = ''
        this.$notify.success('修改成功')
      }).catch(() => {
        loading()
      })
    },
    unLock (row, index) {
      this.$confirm("此操作将(用户名:" + row.username + ")解除登录锁定, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消", type: "warning"
      }
      ).then(() => {
        UnLock(row.userId).then(() => {
          this.getList(this.page)
          this.$notify.success('解除成功')
        }).catch(() => {
          this.$notify.error('解除失败')
        })
      })
    },
    deletes (row, index) {
      this.$confirm("此操作将永久删除该用户(用户名:" + row.username + "), 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消", type: "warning"
      }
      ).then(() => {
        delObj(row.userId).then(() => {
          this.getList(this.page)
          this.$notify.success('删除成功')
        }).catch(() => {
          this.$notify.error('删除失败')
        })
      })
    },
  }
}
</script>
<style lang="scss" scoped>
.user {
  height: 100%;

  &__tree {
    padding-top: 3px;
    padding-right: 20px;
  }

  &__main {
    .el-card__body {
      padding-top: 0;
    }
  }
}

.upload-box {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>

